package com.wuseguang.springcloud.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * map 工具类
 * @author zmc
 *  @since 2019-12-10
 */
public class MapUtil {

    private static Logger logger = LoggerFactory.getLogger(MapUtil.class);

    /**
     * object转map
     * @param object
     * @return
     */
    public static Map<String,Object> objectTurnMap(Object object){

        //创建map集合
        Map<String, Object> map = new HashMap<>();
        //
        Field[] fields  = object.getClass().getDeclaredFields();
        //循环数据
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = null;
            try {
                value = field.get(object);
            } catch (IllegalAccessException e) {
                logger.error("获取vaule失败 e ",e);
            }
            //添加信息
            map.put(name, value);
        }
        return map;
    }

    /**
     * 获取字符传每一个次数出现的次数
     * @param str
     * @return
     */
    public static Map<String, Integer> compress(String str) {
        Map<String, Integer> count = new HashMap<String, Integer>();
        String[] myStrs = str.split(",");
        for (int i = 0; i < myStrs.length; i++) {
            int totalNum = 1;
            String currentStr = myStrs[i];
            if (count.containsKey(currentStr)) {
                totalNum = count.get(currentStr) + 1;
            }
            count.put(currentStr, totalNum);
        }
        return count;
    }

    public static Map<String, Integer> compress( Map<String, Integer> map,String str) {

        String [] s = str.split(",");

        //循环
        for (int i = 0;i<s.length;i++){
            if (!map.containsKey(s[i])){
                map.put(s[i],0);
            }
        }

        return map;
    }
}
